package net.ufrog.common.weixin;

import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import net.ufrog.common.utils.Strings;
import net.ufrog.common.weixin.pojos.AccessToken;
import net.ufrog.common.weixin.pojos.UserInfo;

/**
 * 用户接口
 * 
 * @author ultrafrog
 * @version 1.0, 2015-11-30
 * @since 1.0
 */
public abstract class UserApis {

	public static final String SNSAPI_USERINFO	= "snsapi_userinfo";
	public static final String SNSAPI_BASE		= "snsapi_base";
	
	/**
	 * 生成认证地址
	 * 
	 * @param uri
	 * @param appid
	 * @param state
	 * @param isUserInfo
	 * @return
	 */
	public static String oauthUrl(String uri, String appid, String state, Boolean isUserInfo) {
		String scope = isUserInfo ? SNSAPI_USERINFO : SNSAPI_BASE;
		return String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect", appid, uri, scope, Strings.empty(state, "STATE"));
	}
	
	/**
	 * 获取授权
	 * 
	 * @param appid
	 * @param secret
	 * @param code
	 * @return
	 */
	public static AccessToken oauthAccessToken(String appid, String secret, String code) {
		String url = Apis.url(Apis.SNS_URL, "/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appid, secret, code);
		HttpResponse resp = HttpRequest.get(url).send();
		AccessToken accessToken = Apis.fromJson(resp, AccessToken.class);
		return Apis.checkErr(accessToken);
	}
	
	/**
	 * 刷新授权
	 * 
	 * @param appid
	 * @param refreshToken
	 * @return
	 */
	public static AccessToken oauthRefreshToken(String appid, String refreshToken) {
		String url = Apis.url(Apis.SNS_URL, "/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s", appid, refreshToken);
		HttpResponse resp = HttpRequest.get(url).send();
		AccessToken accessToken = Apis.fromJson(resp, AccessToken.class);
		return Apis.checkErr(accessToken);
	}
	
	/**
	 * 授权信息
	 * 
	 * @param accessToken
	 * @param openid
	 * @return
	 */
	public static UserInfo oauthInfo(String accessToken, String openid) {
		String url = Apis.url(Apis.SNS_URL, "/userinfo?access_token=%s&openid=%s&lang=zh_CN", accessToken, openid);
		HttpResponse resp = HttpRequest.get(url).send();
		UserInfo userInfo = Apis.fromJson(resp, UserInfo.class);
		return Apis.checkErr(userInfo);
	}
	
	/**
	 * 获取用户基本信息
	 * 
	 * @param accessToken
	 * @param openid
	 * @return
	 */
	public static UserInfo info(String accessToken, String openid) {
		String url = Apis.url(Apis.CGI_URL, "/user/info?access_token=%s&openid=%s&lang=zh_CN", accessToken, openid);
		HttpResponse resp = HttpRequest.get(url).send();
		UserInfo userInfo = Apis.fromJson(resp, UserInfo.class);
		return Apis.checkErr(userInfo);
	}
	
	public static void main(String... args) {
		System.out.println(UserApis.oauthUrl("http://www.icengka.com:8080", "wx368f94eceb622f3f", "weixin_oauth", Boolean.FALSE));
	}
}
